package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.DeviceShadowData;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowRequest;
import com.huaweicloud.sdk.iotda.v5.model.ShowDeviceShadowResponse;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.framework.config.IotClientConfig;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.domain.IotMsgNotifyData;
import com.zzyl.nursing.dto.DeviceDataListDto;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceDataService;
import com.zzyl.nursing.vo.DeviceDataListByDayVo;
import com.zzyl.nursing.vo.DeviceDataListByWeekVo;
import com.zzyl.nursing.vo.DeviceHealthVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-27
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService
{
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData)
    {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData)
    {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData)
    {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Override
    public void insertAmqpData(String contentStr) {
        JSONObject jsonObject = JSONUtil.parseObj(contentStr);
        Object object = jsonObject.get("notify_data");

        //1.解析数据
        IotMsgNotifyData iotMsgNotifyData = BeanUtil.toBean(object, IotMsgNotifyData.class);
        //2.设备id 查询数据库
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(new QueryWrapper<Device>().eq("iot_id", deviceId));
        if(device == null){
            throw new RuntimeException("设备不存在");
        }
        //3.数据对象进行分析，获取properties map 数据循环插入到数据库
        iotMsgNotifyData.getBody().getServices().forEach(service -> {

            List<DeviceData> deviceDataList = new ArrayList<>();

            service.getProperties().forEach((key,value)->{

                DeviceData deviceData = BeanUtil.toBean(device, DeviceData.class);
                deviceData.setIotId(deviceId);
                deviceData.setAccessLocation(device.getBindingLocation());
                deviceData.setFunctionId(key);
                deviceData.setDataValue(String.valueOf(value));
                //处理上报时间日期
                LocalDateTime eventTime =  LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
                //日期时区转换
                LocalDateTime alarmTime = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                        .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                deviceData.setAlarmTime(alarmTime);
                deviceData.setId(null);
                deviceDataList.add(deviceData);
            });
           this.saveBatch(deviceDataList);

           //把插入到数据库的数据，同时放入到redis 中
            redisTemplate.opsForHash().put("iot:device_data", deviceId, JSONUtil.toJsonStr(deviceDataList));
        });

    }

    /**
     * 查询健康数据
     * @param iotId
     * @return
     */
    @Autowired
    private IotClientConfig iotClientConfig;
    @Override
    public AjaxResult queryServiceProperties(String iotId) {

//        IoTDAClient client = iotClientConfig.huaWeiIotInstance();
//        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
//        request.withDeviceId(iotId);
//        ShowDeviceShadowResponse response = null;
//        try {
//            response = client.showDeviceShadow(request);
//            System.out.println(response.toString());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        for (DeviceShadowData shadowData : response.getShadow()) {
//            System.out.println(shadowData.toString());
//        }
        List<DeviceData> deviceDataList = deviceDataMapper.selectList(Wrappers.lambdaQuery(DeviceData.class)
                .eq(DeviceData::getIotId, iotId)
                .select(DeviceData::getFunctionId,DeviceData::getAlarmTime,DeviceData::getDataValue)
                .groupBy(DeviceData::getFunctionId));
        List<DeviceHealthVo> deviceHealthVoList = new ArrayList<>();
        for (DeviceData deviceData : deviceDataList) {
            DeviceHealthVo deviceHealthVo = new DeviceHealthVo();
            deviceHealthVo.setFunctionId(deviceData.getFunctionId());
            deviceHealthVo.setEventTime(deviceData.getAlarmTime());
            deviceHealthVo.setValue(deviceData.getDataValue());
            deviceHealthVoList.add(deviceHealthVo);
        }
        return AjaxResult.success(deviceHealthVoList);
    }

    @Override
    public AjaxResult queryDeviceDataListByDay(DeviceDataListDto deviceDataListByDayDto) {
        List<DeviceData> deviceDataList = getDeviceData(deviceDataListByDayDto);
        List<DeviceDataListByDayVo> deviceDataListByDayVoList = new ArrayList<>();
        for (DeviceData deviceData : deviceDataList) {
            DeviceDataListByDayVo deviceDataListByDayVo = new DeviceDataListByDayVo();
            deviceDataListByDayVo.setDataValue(deviceData.getDataValue());
            deviceDataListByDayVo.setDateTime(DateUtil.format(deviceData.getAlarmTime(), "HH.mm"));

            deviceDataListByDayVoList.add(deviceDataListByDayVo);
        }
        return AjaxResult.success(deviceDataListByDayVoList);
    }

    @Override
    public AjaxResult queryDeviceDataListByWeek(DeviceDataListDto deviceDataListByDayDto) {
        List<DeviceData> deviceDataList = getDeviceData(deviceDataListByDayDto);
        List<DeviceDataListByWeekVo> deviceDataListByWeekVoList = new ArrayList<>();
        for (DeviceData deviceData : deviceDataList) {
            DeviceDataListByWeekVo deviceDataListByWeekVo = new DeviceDataListByWeekVo();
            deviceDataListByWeekVo.setDataValue(deviceData.getDataValue());
            deviceDataListByWeekVo.setDateTime(DateUtil.format(deviceData.getAlarmTime(), "MM.dd"));
            deviceDataListByWeekVoList.add(deviceDataListByWeekVo);
        }
        return AjaxResult.success(deviceDataListByWeekVoList);
    }

    private List<DeviceData> getDeviceData(DeviceDataListDto deviceDataListByDayDto) {
        LocalDateTime start = LocalDateTimeUtil.of(deviceDataListByDayDto.getStartTime());
        LocalDateTime end = LocalDateTimeUtil.of(deviceDataListByDayDto.getEndTime());
        List<DeviceData> deviceDataList = this.list(Wrappers.lambdaQuery(DeviceData.class)
                .between(DeviceData::getAlarmTime, start, end)
                .eq(DeviceData::getIotId, deviceDataListByDayDto.getIotId())
                .eq(DeviceData::getFunctionId, deviceDataListByDayDto.getFunctionId())
                .select(DeviceData::getAlarmTime,DeviceData::getDataValue));
        return deviceDataList;
    }
}
